package com.jingbit.ai.activity;

import static com.jingbit.ai.AIApp.TAG;

import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.RectF;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.baidu.aip.asrwakeup3.core.recog.IStatus;
import com.baidu.aip.asrwakeup3.core.recog.MyRecognizer;
import com.baidu.aip.asrwakeup3.core.recog.listener.RecogEventListener;
import com.baidu.aip.asrwakeup3.core.util.AuthUtil;
import com.baidu.aip.asrwakeup3.core.wakeup.MyWakeup;
import com.baidu.aip.asrwakeup3.core.wakeup.WakeUpResult;
import com.baidu.aip.asrwakeup3.core.wakeup.listener.IWakeupListener;
import com.baidu.idl.face.main.attribute.activity.AttributeBaseActivity;
import com.baidu.idl.face.main.attribute.callback.CameraDataCallback;
import com.baidu.idl.face.main.attribute.callback.FaceDetectCallBack;
import com.baidu.idl.face.main.attribute.camera.AttrbuteAutoTexturePreviewView;
import com.baidu.idl.face.main.attribute.camera.CameraPreviewManager;
import com.baidu.idl.face.main.attribute.listener.SdkInitListener;
import com.baidu.idl.face.main.attribute.manager.FaceSDKManager;
import com.baidu.idl.face.main.attribute.model.LivenessModel;
import com.baidu.idl.face.main.attribute.model.SingleBaseConfig;
import com.baidu.idl.face.main.attribute.setting.AttributeSettingActivity;
import com.baidu.idl.face.main.attribute.utils.AttributeConfigUtils;
import com.baidu.idl.face.main.attribute.utils.FaceOnDrawTexturViewUtil;
import com.baidu.idl.face.main.attribute.utils.ToastUtils;
import com.baidu.idl.main.facesdk.FaceInfo;
import com.baidu.idl.main.facesdk.model.BDFaceSDKCommon;
import com.baidu.speech.asr.SpeechConstant;
import com.jingbit.ai.AIApp;
import com.jingbit.ai.R;
import com.jingbit.ai.bean.UserInfo;
import com.jingbit.ai.bt.BluetoothService;
import com.jingbit.ai.bt.BluetoothUtil;
import com.jingbit.ai.helper.GJsonHelper;
import com.jingbit.ai.music.MusicService;
import com.jingbit.ai.music.MusicView;
import com.jingbit.ai.openai.ChatGpt;
import com.jingbit.ai.openai.bean.ChatBean;
import com.jingbit.ai.openai.bean.Choices;
import com.jingbit.ai.service.LocationService;
import com.jingbit.ai.servo.ServoPatrol;
import com.jingbit.ai.utils.AppUtil;
import com.jingbit.ai.utils.CmdUtil;
import com.jingbit.ai.utils.FaceUtil;
import com.jingbit.ai.utils.MediaUtil;
import com.jingbit.ai.utils.SharedPrefsUtil;
import com.jingbit.ai.utils.TTSUtil;
import com.jingbit.ai.weather.HFWeather;
import com.jingbit.ai.weather.listener.IWeatherListener;
import com.jingbit.ai.widget.WaveView;
import com.jingbit.dialog.CustomInputDialog;
import com.jingbit.dialog.CustomListDialog;
import com.unfbx.chatgpt.sse.ConsoleEventSourceListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Response;
import okhttp3.sse.EventSource;

/**
 * author : jingbit
 * date : 2020-02-11 10:30
 * description :
 */
public class FaceActivity extends AttributeBaseActivity implements Handler.Callback, IStatus, IWeatherListener, IWakeupListener {

    /*RGB摄像头图像宽和高*/
    private static final int RGB_WIDTH = SingleBaseConfig.getBaseConfig().getRgbAndNirWidth();
    private static final int RGB_HEIGHT = SingleBaseConfig.getBaseConfig().getRgbAndNirHeight();
    private static final int REQ_VOICEPRINT = 1000;

    private List<String> titles;
    private AttrbuteAutoTexturePreviewView autoTexturePreviewView;
    private TextureView mDrawDetectFaceView;
    private WaveView wv_recog;

    private Button btn_cancel;
    private ImageView iv_qrcode;
    private ImageView iv_biaoqing;
    private AnimationDrawable animDrawable;
    private Paint paint;
    private Paint paintBg;
    private RectF rectF;
    private Timer timer;
    private Handler baseHandler;
    private BluetoothDevice btDevice;
    private BluetoothService btService;
    private ServoPatrol servoPatrol;

    private MyWakeup myWakeup;

    private String registerName;
    private ChatGpt chatGpt;
    private MyRecognizer myRecognizer;
    private RecogEventListener recogEventListener;
    /**
     * 0: 方案1， backTrackInMs > 0,唤醒词说完后，直接接句子，中间没有停顿。
     * 开启回溯，连同唤醒词一起整句识别。推荐4个字 1500ms
     * backTrackInMs 最大 15000，即15s
     * <p>
     * >0 : 方案2：backTrackInMs = 0，唤醒词说完后，中间有停顿。
     * 不开启回溯。唤醒词识别回调后，正常开启识别。
     * <p>
     */
    private final int backTrackInMs = 0;
    private volatile int registerTimeout = 0;//录入人脸超时 120秒
    private volatile long detectedPerson;
    private volatile int connectedBT = 0;//蓝牙连接状态监控
    private volatile int musicResMonitor = 0;//音乐是否加载监控
    private volatile long detectNoSpeech = 0;//没有检测到说话的时长

    private volatile int frequency;
    private volatile int noPersonTimeout = 60;//没有检测到人超时
    private volatile int promotionFrequency = 30;//问候频率,30秒一次
    private RelativeLayout showAtrMessage;
    private MusicService musicService;
    private MusicView musicView;

    private String greeting;//问候词
    private String promotion;//推销词

    private FaceUtil faceUtil;

    private int register = -1;
    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // 实例化 MusicService 对象
            MusicService.MusicBinder musicBinder = (MusicService.MusicBinder) iBinder;
            musicService = musicBinder.getService();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    musicView = new MusicView(FaceActivity.this, musicService);
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService = null;
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initFaceSDK();
        setContentView(R.layout.activity_local);
        SingleBaseConfig.getBaseConfig().setAttribute(true);
        FaceSDKManager.getInstance().initConfig();
        FaceSDKManager.isDetectMask = true;
        initParams();
        initViews();
    }

    private void initFaceSDK() {
        if (FaceSDKManager.initStatus != FaceSDKManager.SDK_MODEL_LOAD_SUCCESS) {
            FaceSDKManager.getInstance().initModel(this, new SdkInitListener() {
                @Override
                public void initStart() {
                }

                @Override
                public void initLicenseSuccess() {
                }

                @Override
                public void initLicenseFail(int errorCode, String msg) {
                }

                @Override
                public void initModelSuccess() {
                    FaceSDKManager.initModelSuccess = true;
                    ToastUtils.toast(FaceActivity.this, "识别模型加载成功，欢迎使用");
                }

                @Override
                public void initModelFail(int errorCode, String msg) {
                    FaceSDKManager.initModelSuccess = false;
                    if (errorCode != -12) {
                        ToastUtils.toast(FaceActivity.this, "识别模型加载失败，请尝试重启应用");
                    }
                }
            });
        }
    }

    private void initParams() {
        rectF = new RectF();
        paint = new Paint();
        paintBg = new Paint();
        titles = new ArrayList<>();
        titles.add("人员注册");
        titles.add("问候词设置");
        titles.add("推销词设置");
        titles.add("属性识别设置");
        titles.add("人脸识别问候频率");
        titles.add("无人超时推销时长");
        titles.add("无人超时推销频率");

        faceUtil = new FaceUtil(this);
        detectNoSpeech = System.currentTimeMillis();
        detectedPerson = System.currentTimeMillis();
        greeting = SharedPrefsUtil.getValue(this, AIApp.TAG, "greeting", "");
        promotion = SharedPrefsUtil.getValue(this, AIApp.TAG, "promotion", "");
        noPersonTimeout = SharedPrefsUtil.getValue(this, AIApp.TAG, "noPersonTimeout", 120);
        promotionFrequency = SharedPrefsUtil.getValue(this, AIApp.TAG, "promotionFrequency", 15);
        FaceUtil.detectFrequency = SharedPrefsUtil.getValue(this, AIApp.TAG, "detectFrequency", 15);

        // 绑定 MusicService
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, mConn, Context.BIND_AUTO_CREATE);
        startService(new Intent(this, LocationService.class));

        timer = new Timer();
        chatGpt = new ChatGpt();
        baseHandler = new Handler();

        servoPatrol = new ServoPatrol(this, 135, 215, 45, 15);
        // 初始化唤醒对象
        myWakeup = new MyWakeup(this, this);
        recogEventListener = new RecogEventListener(this, this);
        myRecognizer = new MyRecognizer(this, recogEventListener);

        TTSUtil.init(this);
        MediaUtil.init();

        btConnect();
        startWakeup();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
//                connectedBT++;
//                musicResMonitor++;
//                registerTimeout++;
//                connectedBT = 0;
//                if (connectedBT == 120) {
//                    btConnect();
//                }
//
//                if (register != -1 && registerTimeout == 240) {
//                    register = -1;
//                    registerTimeout = 0;
//                    doSpeak("录入人脸失败!");
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            btn_cancel.setVisibility(View.GONE);
//                        }
//                    });
//                }
//
////                if (musicResMonitor == 360) {
////                    musicService.loadMusics();
////                    musicResMonitor = 0;
////                }
//
//                if (musicService != null && musicService.isPlaying() && musicView != null) {
//                    myRecognizer.stop();
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            musicView.show();
//                        }
//                    });
//                }
//                if (chatGpt.thinking != -1) {
//                    chatGpt.thinking++;
//                }
//                if (chatGpt.thinking == 10) {
//                    chatGpt.thinking = 0;
//                }
//                if (servoPatrol.isPatrol() && !TTSUtil.isSpeaking() && !musicService.isPlaying()) {
//                    Log.d(AIApp.TAG, "isPatrol: " + frequency);
//                    if (frequency <= 0) {
//                        doSpeak(promotion);
//                        frequency = (Math.abs(frequency) == promotionFrequency * 2) ? promotionFrequency : --frequency;
//                    } else {
//                        frequency--;
//                    }
//                }
//
////                if ((System.currentTimeMillis() - detectedPerson) / 1000 >= noPersonTimeout && register == -1) {
////                    servoPatrol.startPatrol();
////                } else {
////                    servoPatrol.stopPatrol();
////                    frequency = 0;
////                }
//                if (detectNoSpeech != 0 && (System.currentTimeMillis() - detectNoSpeech) / 1000 > 180) {
//                    doSpeak("主人，我去休息啦！", true);
//                    detectNoSpeech = 0;
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            stopAnimation();
//                            hideWaveAnim();
//                        }
//                    });
//                }
                frequency++;
                if (frequency == 20) {
                    doSpeak("喝杨梅荔枝柠檬饮咯,杨梅荔枝柠檬饮是由酸酸甜甜的杨梅、清甜甜口的荔枝、清新的柠檬、凉爽的冰水量制而成，是您夏日助消化,增食欲,祛暑生津,预防中暑的最佳饮品！");
                    frequency = 0;
                }
                if (TTSUtil.isSpeaking()) {
                    startAnimation(R.drawable.speak);
                } else {
                    stopAnimation();
                }
//                faceUtil.clearFace();
            }
        }, 0, 1000);
//        setRgbCameraId(1);
    }

    private void setRgbCameraId(int index) {
        SingleBaseConfig.getBaseConfig().setRBGCameraId(index);
        SingleBaseConfig.getBaseConfig().setRBGCameraId(index);
        AttributeConfigUtils.modityJson();
    }

    private void btConnect() {
//        if (btService == null) btService = new BluetoothService(this, this);
//        if (btDevice == null) btDevice = BluetoothUtil.pair(AIApp.BT_ADDR, AIApp.BT_PWD);
//        if (btDevice == null) {
//            doSpeak("我不能动了！");
//            return;
//        }
//        if (btService.getConnectState() < BluetoothService.STATE_CONNECTING)
//            btService.connect(btDevice);
    }

    private void initViews() {
        Log.d(AIApp.TAG, "initViews");
        mDrawDetectFaceView = findViewById(R.id.face_detection);
        mDrawDetectFaceView.setOpaque(false);
        mDrawDetectFaceView.setKeepScreenOn(true);
        if (SingleBaseConfig.getBaseConfig().getRgbRevert()) {
            mDrawDetectFaceView.setRotationY(180);
        }
        autoTexturePreviewView = findViewById(R.id.face_preview);
        autoTexturePreviewView.setPreviewSize(RGB_WIDTH, RGB_HEIGHT);
        showAtrMessage = findViewById(R.id.rl_face_attr);

        wv_recog = findViewById(R.id.wv_recog);
        btn_cancel = findViewById(R.id.btn_cancel);
        iv_qrcode = findViewById(R.id.iv_qrcode);
        iv_biaoqing = findViewById(R.id.iv_biaoqing);
        iv_biaoqing.setLongClickable(true);
        iv_biaoqing.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (!FaceSDKManager.initModelSuccess) {
                    Toast.makeText(FaceActivity.this, "SDK正在加载模型，请稍后再试", Toast.LENGTH_LONG).show();
                    return false;
                }
                CustomListDialog listDialog = new CustomListDialog(FaceActivity.this);
                listDialog.show("设置管理", titles, new CustomListDialog.IItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent = null;
                        switch (position) {
                            case 0:
                                listDialog.dismiss();
                                doSpeak("请输入您的名字，完成后开始录入人脸，请将您脸庞全部展示在屏幕中间！并开始眨眼或者摇头！");
                                new CustomInputDialog(FaceActivity.this).show("称呼设置", "请设置您的称呼！", "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        registerName = input;
                                        baseHandler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                register = 0;
                                                btn_cancel.setVisibility(View.VISIBLE);
                                            }
                                        }, 2000);
                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                            case 1:
                                new CustomInputDialog(FaceActivity.this).show("问候词设置", greeting, "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        greeting = input;
                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                            case 2:
                                new CustomInputDialog(FaceActivity.this).show("推销词设置", promotion, "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        promotion = input;
                                        SharedPrefsUtil.putValue(FaceActivity.this, AIApp.TAG, "promotion", input);
                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                            case 3:
                                intent = new Intent(FaceActivity.this, AttributeSettingActivity.class);
                                startActivity(intent);
                                break;
                            case 4:
                                new CustomInputDialog(FaceActivity.this).show("人脸识别问候频率(秒)", FaceUtil.detectFrequency + "", "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        try {
                                            FaceUtil.detectFrequency = Integer.parseInt(input);
                                            SharedPrefsUtil.putValue(FaceActivity.this, AIApp.TAG, "detectFrequency", FaceUtil.detectFrequency);
                                        } catch (Exception e) {
                                            ToastUtils.toast(FaceActivity.this, "无效频率！");
                                        }
                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                            case 5:
                                new CustomInputDialog(FaceActivity.this).show("无人超时推销时长(秒)", noPersonTimeout + "", "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        try {
                                            noPersonTimeout = Integer.parseInt(input);
                                            SharedPrefsUtil.putValue(FaceActivity.this, AIApp.TAG, "noPersonTimeout", noPersonTimeout);
                                        } catch (Exception e) {
                                            ToastUtils.toast(FaceActivity.this, "无效时长！");
                                        }
                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                            default:
                                new CustomInputDialog(FaceActivity.this).show("无人超时推销频率(秒)", promotionFrequency + "", "确定", "取消", new CustomInputDialog.IOkayClickListener() {
                                    @Override
                                    public void onOkay(String input) {
                                        try {
                                            promotionFrequency = Integer.parseInt(input);
                                            SharedPrefsUtil.putValue(FaceActivity.this, AIApp.TAG, "promotionFrequency", promotionFrequency);
                                        } catch (Exception e) {
                                            ToastUtils.toast(FaceActivity.this, "无效频率！");
                                        }

                                    }
                                }, new CustomInputDialog.ICancelClickListener() {
                                    @Override
                                    public void onCancel() {
                                    }
                                });
                                break;
                        }
                    }
                });
                return false;
            }
        });

        findViewById(R.id.iv_biaoqing).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (TTSUtil.isSpeaking()) {
                    TTSUtil.doShutup();
                    return true;
                }
                if (musicService != null && musicService.isPlaying()) {
                    musicService.stop();
                    return true;
                }
                return false;
            }
        });

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                btn_cancel.setVisibility(View.GONE);
                register = -1;
            }
        });
    }

    public void showEmotion(String emotion) {
        switch (emotion) {
            case "笑":
                break;
            case "哭":
                break;
            case "生气":
                break;
            case "调皮":
                break;
            default:
                break;
        }
    }

    public void showQrcode(boolean weixin) {
        iv_qrcode.setImageResource(weixin ? R.mipmap.wx_pay : R.mipmap.ali_pay);
        iv_qrcode.setVisibility(View.VISIBLE);
        baseHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doSpeak("你付完了吗？我要收回二维码啦！");
                iv_qrcode.setVisibility(View.GONE);
            }
        }, 60 * 1000);
    }

    private void doSpeak(String word) {
        doSpeak(word, false);
    }

    private void doSpeak(String word, boolean add) {
        TTSUtil.doSpeak(word, add);
        startAnimation(R.drawable.speak);
    }

    private void startAnimation(int animRes) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                synchronized (FaceActivity.this) {
                    if (animDrawable != null && animDrawable.isRunning()) {
                        animDrawable.stop();
                        animDrawable = null;
                        return;
                    }
                    iv_biaoqing.setImageResource(animRes);
                    animDrawable = (AnimationDrawable) iv_biaoqing.getDrawable();
                    animDrawable.start();
                }
            }
        });
    }

    private void stopAnimation() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (animDrawable != null && animDrawable.isRunning()) {
                    animDrawable.stop();
                    animDrawable = null;
                }
                iv_biaoqing.setImageResource(R.drawable.normal);
            }
        });
    }

    private void showWaveAnim() {
        wv_recog.setVisibility(View.VISIBLE);
        wv_recog.startAnim();
    }

    private void hideWaveAnim() {
        wv_recog.setVisibility(View.INVISIBLE);
        wv_recog.stopAnim();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startWakeup();
//        startCameraPreview();
    }

    @Override
    protected void onPause() {
        Log.d(AIApp.TAG, "onPause");
        super.onPause();

    }

    @Override
    protected void onStop() {
        Log.d(AIApp.TAG, "onStop");
        super.onStop();
        if (myWakeup != null) {
            myWakeup.stop();
        }
        if (myRecognizer != null) {
            myRecognizer.stop();
        }
        if (servoPatrol != null) {
            servoPatrol.stopPatrol();
        }
        wv_recog.stopAnim();
        stopAnimation();
    }

    /**
     * 摄像头图像预览
     */
    private void startCameraPreview() {
        // 设置前置摄像头
//        CameraPreviewManager.getInstance().setCameraFacing(CameraPreviewManager.CAMERA_FACING_FRONT);
        // 设置后置摄像头
        // CameraPreviewManager.getInstance().setCameraFacing(CameraPreviewManager.CAMERA_FACING_BACK);
        // 设置USB摄像头
//        if (SingleBaseConfig.getBaseConfig().getRBGCameraId() != -1) {
        CameraPreviewManager.getInstance().setCameraFacing(SingleBaseConfig.getBaseConfig().getRBGCameraId());
//        } else {
//            CameraPreviewManager.getInstance().setCameraFacing(CameraPreviewManager.CAMERA_USB);
//        }
        CameraPreviewManager.getInstance().setDisplayOrientation(90);
        CameraPreviewManager.getInstance().startPreview(this, autoTexturePreviewView, RGB_WIDTH, RGB_HEIGHT, new CameraDataCallback() {
            @Override
            public void onGetCameraData(byte[] rgbData, Camera camera, int srcWidth, int srcHeight) {
                Log.d(AIApp.TAG, "onGetCameraData：" + rgbData);
                handleCameraData(rgbData);
            }
        });
    }

    private void handleCameraData(byte[] rgbData) {
        if (rgbData != null) {
            FaceSDKManager.getInstance().onAttrDetectCheck(rgbData, null, null, RGB_HEIGHT, RGB_WIDTH, 1, new FaceDetectCallBack() {
                @Override
                public void onFaceDetectCallback(final LivenessModel livenessModel) {
                    // 检测结果输出
                    if (livenessModel != null) {
                        final FaceInfo faceInfo = livenessModel.getFaceInfo();
                        Log.d(AIApp.TAG, "onFaceDetectCallback: " + (faceInfo != null ? faceInfo.score : 0));
                        if (faceInfo != null && faceInfo.score >= 0.3) {
                            detectedPerson = System.currentTimeMillis();
                            if (register != -1 && faceInfo.score >= 0.75) {
                                if (musicService.isPlaying()) {
                                    musicService.stop();
                                }
                                faceUtil.addFace(FaceActivity.this, registerName, faceInfo);
                                if (register == 1) {
                                    register = -1;
                                    doSpeak("录入人脸成功！");
                                    btn_cancel.setVisibility(View.GONE);
                                } else {
                                    doSpeak("录入第" + (register + 1) + "次成功！请再录入一次！");
                                }
                                register++;
                            } else {
                                if (musicService.isPlaying()) {
                                    AppUtil.setVolumeByVol(FaceActivity.this, 10);
                                }
                                String callName = "";
                                String sex = faceInfo.gender == BDFaceSDKCommon.BDFaceGender.BDFACE_GENDER_FEMALE ? "女" : faceInfo.gender == BDFaceSDKCommon.BDFaceGender.BDFACE_GENDER_MALE ? "男" : "婴儿";
                                if (faceInfo.score >= 0.6) {
                                    if (faceInfo.age <= 10 && faceInfo.age > 0) {
                                        callName = "小朋友，你好聪明呀";
                                    } else if (faceInfo.age <= 20 && faceInfo.age > 10) {
                                        callName = sex.equals("男") ? "小哥哥，你好帅呀" : "小姐姐，你好漂亮呀";
                                    } else if (faceInfo.age <= 40 && faceInfo.age > 20) {
                                        callName = sex.equals("男") ? "大哥哥，你好帅呀" : "大姐姐，你好漂亮呀";
                                    } else if (faceInfo.age <= 50 && faceInfo.age > 40) {
                                        callName = sex.equals("男") ? "叔叔，您好帅呀" : "阿姨，您好漂亮呀";
                                    } else if (faceInfo.age > 50) {
                                        callName = sex.equals("男") ? "爷爷，您好" : "奶奶，您好";
                                    }
                                } else {
                                    callName = "您好,";
                                }

                                UserInfo userInfo = faceUtil.doCompare(faceInfo.landmarks, 0.7d);
                                Log.d(AIApp.TAG, "doCompare111：" + faceInfo.age + "---" + callName + "---" + userInfo);
                                if (userInfo == null) {
                                    doSpeak(callName + greeting, true);
                                    faceUtil.addFace(FaceActivity.this, "", faceInfo);
                                } else {
                                    int timeGap = (int) ((System.currentTimeMillis() - userInfo.getTimestamp()) / 1000);
                                    Log.d(AIApp.TAG, "doCompare222: " + timeGap + "---" + FaceUtil.detectFrequency);
                                    if (!TextUtils.isEmpty(userInfo.getName())) {
                                        if (timeGap > (FaceUtil.detectFrequency / 3)) {
                                            faceUtil.resetFace(userInfo);
                                            doSpeak(userInfo.getName() + (sex.equals("男") ? "你好帅！" : "你好漂亮！"));
                                        }
                                    } else {
                                        if (timeGap > FaceUtil.detectFrequency) {
                                            faceUtil.resetFace(userInfo);
                                            doSpeak(callName + greeting);
                                        }
                                    }
                                }
                                if (musicService.isPlaying()) {
                                    AppUtil.setVolumeByVol(FaceActivity.this, 90);
                                }
                            }
                        }

                    }
                }

                @Override
                public void onTip(int code, String msg) {
                }

                @Override
                public void onFaceDetectDarwCallback(LivenessModel livenessModel) {
                    Log.d(AIApp.TAG, "onFaceDetectDarwCallback：" + livenessModel.getFaceInfo());
                    showFrame(livenessModel);
                }
            });
        }
    }

    /**
     * 绘制人脸框
     */
    private void showFrame(final LivenessModel model) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Canvas canvas = mDrawDetectFaceView.lockCanvas();
                if (canvas == null) {
                    mDrawDetectFaceView.unlockCanvasAndPost(canvas);
                    showArtLinerGone();
                    return;
                }
                if (model == null) {
                    // 清空canvas
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    mDrawDetectFaceView.unlockCanvasAndPost(canvas);
                    showArtLinerGone();
                    return;
                }
                FaceInfo[] faceInfos = model.getTrackFaceInfo();
                if (faceInfos == null || faceInfos.length == 0) {
                    // 清空canvas
                    canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                    mDrawDetectFaceView.unlockCanvasAndPost(canvas);
                    showArtLinerGone();
                    return;
                }
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                FaceInfo faceInfo = faceInfos[0];

                rectF.set(FaceOnDrawTexturViewUtil.getFaceRectTwo(faceInfo));
                // 检测图片的坐标和显示的坐标不一样，需要转换。
                FaceOnDrawTexturViewUtil.mapFromOriginalRect(rectF, autoTexturePreviewView, model.getBdFaceImageInstance());

                paint.setColor(Color.parseColor("#00baf2"));
                paintBg.setColor(Color.parseColor("#00baf2"));

                paint.setStyle(Paint.Style.FILL);
                paintBg.setStyle(Paint.Style.FILL);
                // 画笔粗细
                paint.setStrokeWidth(8);
                paint.setAntiAlias(true);
                paintBg.setStrokeWidth(13);
                paintBg.setAntiAlias(true);
                paintBg.setAlpha(90);

                if (showAtrMessage.getVisibility() == View.GONE) {
                    showAtrMessage.setVisibility(View.VISIBLE);
                }

                if (faceInfo.width > faceInfo.height) {
                    if (!SingleBaseConfig.getBaseConfig().getRgbRevert()) {

                        FaceOnDrawTexturViewUtil.drawRect(canvas, rectF, paint, 5f, 50f, 25f);
                        if (rectF.centerY() < autoTexturePreviewView.getHeight() * 0.6) {
                            showAtrMessage.setTranslationX(rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() + rectF.height() / 2);
                        } else {
                            showAtrMessage.setTranslationX(rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() - rectF.width() - showAtrMessage.getHeight());
                        }
                    } else {
                        FaceOnDrawTexturViewUtil.drawRect(canvas, rectF, paint, 5f, 50f, 25f);
                        if (rectF.centerY() < autoTexturePreviewView.getHeight() * 0.6) {
                            showAtrMessage.setTranslationX(autoTexturePreviewView.getWidth() - rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() + rectF.width() / 2);
                        } else {
                            showAtrMessage.setTranslationX(autoTexturePreviewView.getWidth() - rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() - rectF.width() - showAtrMessage.getHeight());
                        }
                    }
                } else {
                    if (!SingleBaseConfig.getBaseConfig().getRgbRevert()) {
                        FaceOnDrawTexturViewUtil.drawRect(canvas, rectF, paint, 5f, 50f, 25f);
                        if (rectF.centerY() < autoTexturePreviewView.getHeight() * 0.6) {
                            showAtrMessage.setTranslationX(rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() + rectF.width() / 2);
                        } else {
                            showAtrMessage.setTranslationX(rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() - rectF.width() - showAtrMessage.getHeight());
                        }
                    } else {
                        FaceOnDrawTexturViewUtil.drawRect(canvas, rectF, paint, 5f, 50f, 25f);
                        if (rectF.centerY() < autoTexturePreviewView.getHeight() * 0.6) {
                            showAtrMessage.setTranslationX(autoTexturePreviewView.getWidth() - rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() + rectF.width() / 2);
                        } else {
                            showAtrMessage.setTranslationX(autoTexturePreviewView.getWidth() - rectF.centerX());
                            showAtrMessage.setTranslationY(rectF.centerY() - rectF.width() - showAtrMessage.getHeight());
                        }
                    }
                }

                // 清空canvas
                mDrawDetectFaceView.unlockCanvasAndPost(canvas);
            }
        });
    }

    public void showArtLinerGone() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showAtrMessage.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onWeather(String info) {
        HFWeather.getInstance().setWeatherListener(null);
        HFWeather.getInstance().setType(0);
        HFWeather.getInstance().setIndex(-1);
        TTSUtil.doSpeak(info);
    }

    private void startWakeup() {
        Map<String, Object> params = AuthUtil.getParam();
        params.put(SpeechConstant.WP_WORDS_FILE, "assets:///WakeUp.bin");
        // "assets:///WakeUp.bin" 表示WakeUp.bin文件定义在assets目录下

        // params.put(SpeechConstant.ACCEPT_AUDIO_DATA,true);
        // params.put(SpeechConstant.IN_FILE,"res:///com/baidu/android/voicedemo/wakeup.pcm");
        // params里 "assets:///WakeUp.bin" 表示WakeUp.bin文件定义在assets目录下
        myWakeup.start(params);
    }

    @Override
    public boolean handleMessage(Message msg) {
//        Log.d(AIApp.TAG, "handleMessage：" + msg);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                switch (msg.what) {
                    case BluetoothService.MSG_STATE_CHANGE:
                        switch (msg.arg1) {
                            case BluetoothService.STATE_CONNECTED:
                                doSpeak("我能动了！", true);
                                btService.write(BluetoothService.MSG_RESET_SIGN, 0);
                                try {
                                    Thread.sleep(50);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                btService.write(BluetoothService.MSG_PWM1_SIGN, BluetoothUtil.angleToPwm(80, BluetoothService.MSG_PWM1_ANGLE_HALF));
                                break;
                            case BluetoothService.STATE_CONNECTING:
                                doSpeak("控制身体中...", true);
                                break;
                            case BluetoothService.STATE_LISTEN:
                            case BluetoothService.STATE_NONE:
                                doSpeak("我不能动了！", true);
                                break;
                        }
                        break;
                    case BluetoothService.MSG_READ:
                        byte[] readBuf = (byte[]) msg.obj;
                        // construct a string from the valid bytes in the buffer
                        String readMessage = new String(readBuf, 0, msg.arg1);
                        Log.d(AIApp.TAG, "MSG_READ：" + readMessage);
                        break;
                    case ServoPatrol.MSG_CODE:
                        Log.d(AIApp.TAG, "ServoPatrol: " + msg.arg1 + "---" + BluetoothUtil.angleToPwm(msg.arg1, BluetoothService.MSG_PWM3_ANGLE_HALF));
                        btService.write(BluetoothService.MSG_PWM3_SIGN, BluetoothUtil.angleToPwm(msg.arg1, BluetoothService.MSG_PWM3_ANGLE_HALF));
                        break;
                    //STATUS_SPEAKING 用户开始说话到用户说话完毕前
                    //STATUS_RECOGNITION 用户说话完毕后，识别结束前
                    //STATUS_FINISHED 获得最终识别结果
                    case STATUS_ASR:
                        String asr_word = (String) msg.obj;
                        Log.d(AIApp.TAG, "handleMessage STATUS_ASR : " + msg.arg1 + "---" + asr_word);
                        switch (msg.arg1) {
                            case STATUS_ASR_READY:
                                break;
                            case STATUS_ASR_SPEAKING:
                                break;
                            case STATUS_ASR_VOLUME:
                                showWaveAnim();
                                wv_recog.setVolume(msg.arg2);
                                break;
                            case STATUS_ASR_RECOGING:
                                break;
                            case STATUS_ASR_PART_FINISHED:
                                hideWaveAnim();
                                Log.d(AIApp.TAG, "handleMessage STATUS_ASR_PART_FINISHED : " + asr_word + "---" + TTSUtil.isSpeaking());
                                if (TTSUtil.isSpeaking()) {
                                    String breakCmd = TTSUtil.isBreakCmd(asr_word, 0.7d);
                                    if (!TextUtils.isEmpty(breakCmd)) {
                                        Log.d(AIApp.TAG, "handleMessage STATUS_ASR_PART_FINISHED isBreakCmd: " + breakCmd + "---" + asr_word);
                                        doSpeak("好的！");
                                        TTSUtil.doShutup();
                                    }
                                    break;
                                }
                                break;
//                            case STATUS_ASR_FINAL_FINISHED:
//                                Log.d(AIApp.TAG, "handleMessage STATUS_ASR_FINAL_FINISHED : " + asr_word);
//                                break;
                            case STATUS_ASR_FAILED:
                                doSpeak("我没明白你的意思哦！");
                                hideWaveAnim();
                                break;
                            case STATUS_ASR_FINAL_FINISHED:
                                detectNoSpeech = System.currentTimeMillis();
                                MediaUtil.playSoundFromA(FaceActivity.this, "dong.wav");
                                Log.d(AIApp.TAG, "onResult: " + asr_word);
                                if (TTSUtil.isSpeaking(System.currentTimeMillis())) {
                                    return;
                                }
                                String[] rets = CmdUtil.isCmd(asr_word);
                                if (rets != null) {
                                    Log.d(AIApp.TAG, "onResult isCmd: " + rets[0] + "---" + asr_word);
                                    try {
                                        CmdUtil.executeCmd(FaceActivity.this, musicService, btService, rets[0], rets[1]);
                                    } catch (CameraAccessException e) {
                                        throw new RuntimeException(e);
                                    }
                                    return;
                                }
                                if (musicService.isPlaying()) {
                                    return;
                                }
                                StringBuffer sb = new StringBuffer();
                                chatGpt.startChat(new ConsoleEventSourceListener() {
                                    @Override
                                    public void onEvent(EventSource eventSource, String id, String type, String data) {
                                        Log.d(AIApp.TAG, "onResult chatgpt onEvent: " + id + "---" + type + "---" + data);
                                        if (TextUtils.isEmpty(data)) {
                                            ChatGpt.thinking = -1;
                                            doSpeak("我没明白你的意思哦！");
                                            return;
                                        }

                                        try {
                                            if (!TextUtils.isEmpty(data)) {
                                                ChatBean chatBean = GJsonHelper.parseJson(data, ChatBean.class);
                                                if (chatBean != null && !chatBean.getChoices().isEmpty()) {
                                                    for (Choices choice : chatBean.getChoices()) {
                                                        if (choice.getDelta() != null && !TextUtils.isEmpty(choice.getDelta().getContent())) {
                                                            String content = choice.getDelta().getContent();
                                                            sb.append(content);
                                                            if (content.equals(",") || content.equals("，") || content.equals("。") || content.equals(".")) {
                                                                doSpeak(sb.toString(), true);
                                                                sb.setLength(0);
                                                            }
                                                        }
                                                    }
                                                    if (chatBean.getChoices().get(0).getFinish_reason().equals("stop")) {
                                                        ChatGpt.thinking = -1;
                                                        if (!TextUtils.isEmpty(sb.toString())) {
                                                            doSpeak(sb.toString(), true);
                                                            sb.setLength(0);
                                                        }
                                                    }
                                                }
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(EventSource eventSource, Throwable t, Response response) {
                                        Log.d(AIApp.TAG, "onResult chatgpt onFailure: " + t.getMessage());
                                        ChatGpt.thinking = -1;
                                        doSpeak("我没明白你的意思哦！");
                                    }
                                }, asr_word);
                                break;
                            case STATUS_ASR_STOPPED:
                                break;
                            case STATUS_ASR_LONG_STOPPED:
                            case STATUS_ASR_EXIT:
                                Log.d(AIApp.TAG, "handleMessage STATUS_ASR_LONG_STOPPED & STATUS_ASR_EXIT: ");
                                hideWaveAnim();
                                startWakeup();
                                break;
                        }
                        break;
                }
            }
        });
        return false;
    }


    @Override
    public void onWakeupSuccess(String word, WakeUpResult result) {
        doSpeak("恩,我在?");
        doVoiceRecog(true);
    }

    @Override
    public void onWakeupStoped() {
    }

    @Override
    public void onWakeupError(int errorCode, String errorMessge, WakeUpResult result) {
        Log.d(TAG, "onWakeupError：" + errorMessge);
    }

    @Override
    public void onASrAudio(byte[] data, int offset, int length) {
    }

    private void doVoiceRecog(boolean restart) {
        // 此处 开始正常识别流程
        Map<String, Object> params = AuthUtil.getParam();
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, true);
        params.put(SpeechConstant.VAD_ENDPOINT_TIMEOUT, 1000);
//        params.put(SpeechConstant.ACCEPT_AUDIO_DATA, true);
        params.put(SpeechConstant.VAD, SpeechConstant.VAD_DNN);
        // 使用1537中文模型。其它PID参数请看文档
        params.put(SpeechConstant.ASR_ENABLE_NUMBERFORMAT, true);
//        params.put(SpeechConstant.ASR_PUNCTUATION_MODE,true);
        params.put(SpeechConstant.SOUND_START, R.raw.bdspeech_recognition_start);
        params.put(SpeechConstant.SOUND_ERROR, R.raw.bdspeech_recognition_error);
        params.put(SpeechConstant.SOUND_END, R.raw.bdspeech_recognition_cancel);
        params.put(SpeechConstant.SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
        params.put(SpeechConstant.PID, MODE_PID);
//        params.put(SpeechConstant.OUT_FILE, asr_speech_file.getAbsolutePath());
        params.put(SpeechConstant.BDS_ASR_ENABLE_LONG_SPEECH, true);
        if (backTrackInMs > 0) {
            // 方案1  唤醒词说完后，直接接句子，中间没有停顿。开启回溯，连同唤醒词一起整句识别。
            // System.currentTimeMillis() - backTrackInMs ,  表示识别从backTrackInMs毫秒前开始
            params.put(SpeechConstant.AUDIO_MILLS, System.currentTimeMillis() - backTrackInMs);
        }
        if (restart) {
            myRecognizer.cancel();
        }
        myRecognizer.start(params);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(AIApp.TAG, "onActivityResult: " + requestCode + "---" + resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQ_VOICEPRINT) {
//                voicePrintInfos = VoicePrintNative.getVoicePrintInfos();
            }
        }
    }

    @Override
    protected void onDestroy() {
        timer.cancel();
        myRecognizer.release();
        btService.write(BluetoothService.MSG_RESET_SIGN, 0);
        // 解除绑定 MusicService
        unbindService(mConn);
        super.onDestroy();
        FaceSDKManager.isDetectMask = false;
        CameraPreviewManager.getInstance().stopPreview();
        // 关闭属性检测
        SingleBaseConfig.getBaseConfig().setAttribute(false);
        FaceSDKManager.getInstance().initConfig();
    }

}
